let express = require("express");
let mysql = require("mysql");

// 导入格式化formData中的数据中间键 body-parser
let bodyParser = require("body-parser");
let dataFormat = bodyParser.urlencoded();

let { createProxyMiddleware: proxy } = require("http-proxy-middleware");

// 连接数据库
let connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "wisdombusiness",
});
connection.connect();

let app = express();

app.use(express.static("./"));

app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});

// https://console.e.360.cn/api/v1/eshop/GetGoodsList
app.use(
  "/api",
  proxy({
    target: " https://console.e.360.cn/",
    changeOrigin: true,
    pathRewrite: { "/^api": "/" },
  })
);

// 注册
app.post("/register", dataFormat, (req, res) => {
  console.log(req.body);
  // console.log(res);
  let { tel, password } = req.body;
  // console.log(tel);
  // console.log(password);

  // 得到电话和密码后去数据库查看是否存在
  // SELECT * FROM `user` WHERE `tel` LIKE '17798315323' AND `password` LIKE '12345678'
  connection.query(
    `SELECT * FROM user WHERE tel LIKE '${tel}'`,
    (err, data) => {
      // res.send(data);
      if (data[0]) {
        res.send({
          code: false,
          msg: "该用户已经注册",
        });
        return;
      }
      connection.query(
        `INSERT INTO user VALUES(${null},'${tel}','${password}')`,
        (error, datas) => {
          console.log(datas);
          if (!datas) {
            res.send({ code: false, msg: "添加错误" });
            return;
          }
          res.send({ code: true, msg: "注册成功" });
        }
      );
    }
  );
});

// 登录
app.get("/login", (req, res) => {
  console.log(req.query);
  let { tel, password } = req.query;
  // SELECT * FROM `user` WHERE `id` = 1 AND `tel` LIKE '17798315323' AND `password` LIKE '12345678'
  connection.query(
    `SELECT * FROM user WHERE tel LIKE '${tel}' AND password LIKE '${password}'`,
    (err, data) => {
      if (data[0]) {
        res.send({
          code: true,
          msg: "登录成功",
        });
        return;
      }
      res.send({
        code: false,
        msg: "用户名或密码错误",
      });
    }
  );
});

// 精品课程
// https://y.lwt.360.cn/lwt_api/config_column_list
app.use(
  "/lwt_api",
  proxy({
    target: "https://y.lwt.360.cn/",
    changeOrigin: true,
    pathRewrite: { "/^lwt_api": "/" },
  })
);

// 案例咨询
// https://tobadmin.e.360.cn/api/v1/product/GetHot
app.use(
  "/api",
  proxy({
    target: "https://tobadmin.e.360.cn/",
    changeOrigin: true,
    pathRewrite: { "/^api": "/" },
  })
);

app.listen("9090", () => {
  console.log("running port 9090");
});
